const app = getApp()

var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
qqmapsdk = new QQMapWX({
  key: 'Q6IBZ-QHNR2-XOGUX-C7C7F-R3JV7-OUB67' //申请自己的开发者密钥
});

var date = new Date();
var currentHours = date.getHours();
var currentMinute = date.getMinutes();

Page({
  data: {
    globalData: app.globalData,
    globalMapData: app.globalData.map,

    //地图属性
    scale: 20,
    latitude: 0,
    longitude: 0,
    address: '',
    bluraddress: '',

    //---切换---
    cType: 1,
    isGoBtn: false,
    isGotoBackBtn: false,

    //动态高度
    mapHeight: '',
    mapBottom: 364,

    //时间属性
    nowYear: '',
    startMonthDay: '',
    startHM: '',
    endMonthDay: '',
    endHM: '',

    //时间选择器
    dateArr: [{
      value: '2018-11-17 10:19#24:00'
    }, {
      value: '2018-11-18 11:29#19:11'
    }, {
      value: '2018-11-19 12:09#21:41'
    }, {
      value: '2018-11-20 09:08#22:20'
    }],
    startDate: [],
    endDate: [],

    //用户 && 订单
    userInfo: {},
    orderInfo: {},

  },
  // -------------默认页面事件 -------------
  onLoad: function(options) {
    var that = this;

    // //验证登录，如果当前全局没有值，读取setStrong，如果还没有，就去登录页面
    // app.userLogin();
    //获取用户数据缓存
    wx.getStorage({
      key: 'users',
      success: function (e) {
        app.globalData.userInfo = e.data;
        that.setData({
          userInfo: e.data,
          globalData: app.globalData,
        })
      }
    })

    let sID = options.sID;
    let ctypeID = options.ctypeID
    let sLat = options.slat;
    let sLng = options.slng;

    //其他
    if (sID == '1') {
      this.setData({
        latitude: sLat,
        longitude: sLng,
        cType: ctypeID
      });
      that.setMapHeight();
    }
    if (sID == '2') {
      this.setData({
        cType: ctypeID
      });
      that.setMapHeight();
    }

    //如果全局有目的地经纬度
    if (app.globalData.map.endLatitude != '' && app.globalData.map.endLongitude != '') {
      var that = this;
      that.setData({
        isGoBtn: true,
        isGotoBackBtn: true,
        longitude: app.globalData.map.strLongitude,
        latitude: app.globalData.map.strLatitude,
        markers: [{
          iconPath: "../../pages/image/markerStart.png",
          id: 0,
          latitude: app.globalData.map.strLatitude,
          longitude: app.globalData.map.strLongitude,
          width: 30,
          height: 44
        }, {
          iconPath: "../../pages/image/markerEnd.png",
          id: 1,
          longitude: app.globalData.map.endLongitude,
          latitude: app.globalData.map.endLatitude,
          width: 30,
          height: 44
        }],
      });
      that.setMapHeight();
    }

    if (this.data.latitude == '0' && this.data.longitude == '0') {
      this.setData({
        latitude: app.globalData.map.strLatitude,
        longitude: app.globalData.map.strLongitude
      })

    }

    // 如果全局有经纬度
    if (app.globalData.map.strLatitude != '' && app.globalData.map.strLongitude != '' && this.data.Latitude == undefined && this.data.Longitude == undefined) {
      that.setData({
        globalMapData: app.globalData.map,
      });

      // if (this.data.curIndex == '1') {
      //   this.setMapHeight();
      // }

    } else {
      //获取位置信息
      if (this.data.Latitude == undefined && this.data.Longitude == undefined) {
        wx.getLocation({
          type: "gcj02",
          success: (res) => {
            //赋值到全局起始经纬度
            app.globalData.map.strLatitude = res.latitude;
            app.globalData.map.strLongitude = res.longitude;
            this.setData({
              longitude: res.longitude,
              latitude: res.latitude,
            })
            var that = this;
            qqmapsdk.reverseGeocoder({
              location: {
                latitude: res.latitude,
                longitude: res.longitude,
              },
              success: function(res) {
                app.globalData.map.startAddress = res.result.formatted_addresses.recommend;
                app.globalData.map.strLatitude = res.result.location.lat;
                app.globalData.map.strLongitude = res.result.location.lng;
                that.setData({
                  address: res.result.address,
                  bluraddress: res.result.formatted_addresses.recommend,
                  globalMapData: app.globalData.map,
                });
              },
            });
            //console.log('获取位置信息 ' + app.globalData.map.strLatitude, app.globalData.map.strLongitude)
          }
        })
        that.setMapHeight();
      }
    }

  },
  onReady: function() {
    var that = this;
    this.mapCtx = wx.createMapContext("xMap");
    setTimeout(function() {
      that.setMapHeight();
    }, 300);
  },

  //-----------点击跳转类----------
  //跳转订单页面
  goToPage: function(e) {
    wx.reLaunch({
      url: '../order/order',
      delta: 1
    })
  },
  //跳转地址搜索页面
  goToSearch: function(e) {
    if (this.data.cType == '1' && app.globalData.startDate == '') {
      wx.showToast({
        title: '请确定日期',
        icon: 'none',
        mask: true,
        duration: 2000
      })
    } else {
      wx.navigateTo({
        url: '/pages/search/search?searchID=' + e.currentTarget.dataset.id + '&curIndex=' + e.currentTarget.dataset.curindex + '&ctypeid=' + this.data.cType
      })
    }
  },
  // 前往用户页面
  goToUI: function(e) {
    //navigateBack
    wx.navigateTo({
      url: '/pages/user/userInfo'
    })
  },
  //实时与预约点击
  cTypeTap: function(e) {
    this.setData({
      cType: e.target.dataset.id,
      isGoBtn: false,
    });

    if (e.target.dataset.id == '1' || e.target.dataset.id == '0') {
      var that = this;
      this.setMapHeight();
    }

  },
  //调用规划驾车路线
  gogo: function(e) {
    this.driving();
    this.setData({
      isGoBtn: false,
    })
    this.ClearMapGPS();
  },
  //-----------map设置----------
  //移动选点
  bindregionchange: function(e) {
    if (app.globalData.map.endLatitude == '' || app.globalData.map.endLongitude == '' || app.globalData.map.endLatitude == '0' || app.globalData.map.endLongitude == '0' || app.globalData.map.endLatitude == undefined || app.globalData.map.endLongitude == undefined) {
      var that = this
      this.mapCtx.getCenterLocation({
        success: function(res) {
          app.globalData.strLatitude = res.latitude
          app.globalData.strLongitude = res.longitude
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude,
            },
            success: function(res) {
              app.globalData.map.startAddress = res.result.formatted_addresses.recommend;
              app.globalData.map.strLatitude = res.result.location.lat;
              app.globalData.map.strLongitude = res.result.location.lng;
              that.setData({
                address: res.result.address,
                bluraddress: res.result.formatted_addresses.recommend,
                globalMapData: app.globalData.map
              });
            },
          });
        }
      })
    }

  },
  //左下点击回到当前定位
  moveToLocation: function() {
    console.log('moveToLocation---')
    this.mapCtx.moveToLocation()
  },
  //驾车路线规划
  driving: function() {
    // var _this = this;
    // //网络请求设置
    // var opt = {
    //   //WebService请求地址，from为起点坐标，to为终点坐标，开发key为必填
    //   url: 'https://apis.map.qq.com/ws/direction/v1/driving/?from=' + app.globalData.map.strLatitude + ',' + app.globalData.map.strLongitude + '&to=' + app.globalData.map.endLatitude + ',' + app.globalData.map.endLongitude + '&key=Q6IBZ-QHNR2-XOGUX-C7C7F-R3JV7-OUB67&',
    //   method: 'GET',
    //   dataType: 'json',
    //   //请求成功回调
    //   success: function(res) {
    //     _this.setData({
    //       polyline: [{
    //         points: [{
    //           latitude: app.globalData.map.strLatitude,
    //           longitude: app.globalData.map.strLongitude,
    //         }, {
    //           longitude: app.globalData.map.endLongitude,
    //           latitude: app.globalData.map.endLatitude
    //         }],
    //         color: "#ff6600",
    //         width: 6,
    //         dottedLine: true,
    //         arrowLine: true,
    //         borderColor: "#000",
    //         borderWidth: 5
    //       }]
    //     });
    //     //console.log(res);
    //     var ret = res.data
    //     if (ret.status != 0) return; //服务异常处理
    //     var coors = ret.result.routes[0].polyline,
    //       pl = [];
    //     //坐标解压（返回的点串坐标，通过前向差分进行压缩）
    //     var kr = 1000000;
    //     for (var i = 2; i < coors.length; i++) {
    //       coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
    //     }
    //     //将解压后的坐标放入点串数组pl中
    //     for (var i = 0; i < coors.length; i += 2) {
    //       pl.push({
    //         latitude: coors[i],
    //         longitude: coors[i + 1]
    //       })
    //     }
    //     //设置polyline属性，将路线显示出来
    //     _this.setData({
    //       polyline: [{
    //         points: pl,
    //         color: '#FF0000DD',
    //         width: 2
    //       }]
    //     })
    //   }
    // };
    // wx.request(opt);
  },
  //地图高度计算
  // setMapHeight() {
  //   var that = this;

  //   var query = wx.createSelectorQuery();
  //   query.select('.xContent').boundingClientRect(function (e) {
  //     that.setData({
  //       mapHeight: (wx.getSystemInfoSync().windowHeight - e.height) + 'px'
  //     })
  //     console.log('.xContent', e.height)
  //   }).exec();

  //   var query = wx.createSelectorQuery();
  //   query.select('.Map').boundingClientRect(function (e) {
  //     console.log('.Map', e.height)
  //   }).exec();
  // },
  setMapHeight() {
    var that = this;
    // 实时
    //console.log('cType', this.data.cType, this.data.isGoBtn)   
    if (that.data.isGoBtn == true) {
      that.setData({
        mapBottom: 100
      })
    } else if (that.data.cType == 0) {
      that.setData({
        mapBottom: 298
      })
    } else if (that.data.cType == 1) {
      that.setData({
        mapBottom: 364
      })
    }
  },
  //--------时间选择器----------
  // 回调
  bindStartMultiPickerChange(time) {
    var that = this;
    console.log('bindStartMultiPickerChange 回调', time);
    app.globalData.startDate = time.detail[0];
    this.setData({
      globalData: app.globalData,
    })
  },
  //订单事件处理
  shareCarForm: function(event) {
    var that = this;
    var orderInfo = event.detail.value;
    orderInfo.openId = app.openId;
    orderInfo.name = app.globalData.userInfo.name;
    orderInfo.phone = app.globalData.userInfo.phone;
    orderInfo.storeId = app.globalData.userInfo.storeId;
    orderInfo.getPlace = app.globalData.map.startAddress;
    orderInfo.backPlace = app.globalData.map.endAddress;
    orderInfo.ordergetGPS = app.globalData.map.strLongitude + ',' + app.globalData.map.strLatitude;
    orderInfo.orderbackGPS = app.globalData.map.endLongitude + ',' + app.globalData.map.endLatitude;
    orderInfo.storeId = app.globalData.userInfo.storeId;
    
    if (this.data.cType == '0') {
      orderInfo.dordergetDate = app.globalData.nowDate2;
      if (orderInfo == '' || orderInfo.openId == '' || orderInfo.name == '' || orderInfo.phone == '' || orderInfo.ordergetGPS == '' || orderInfo.orderbackGPS == '' || orderInfo.backPlace == '' || orderInfo.dordergetDate == '' || orderInfo.dordergetDate == undefined) {
        console.log('orderInfo', orderInfo);
        wx.showToast({
          title: '请确认信息完整',
          icon: 'none',
          mask: true,
          duration: 2000
        })
      } else {
        console.log('网约车---', orderInfo)
        that.moveToLocation();
        app.request({
          url: "/reserveCarSave",
          data: orderInfo,
          success: function(res) {
            that.ClearMapGPS();
            that.moveToLocation();
            wx.showToast({
              title: '提交订单成功',
              icon: 'success',
              mask: true,
              duration: 2000,
              success: function() {
                setTimeout(function() {
                  wx.reLaunch({
                    url: '/pages/order/order'
                  })
                }, 2000);
              }
            })
          }, fail: function (res) {
            that.ClearMapGPS();
            that.moveToLocation();
          }
        })
        that.moveToLocation();
      }
    } else {
      orderInfo.dordergetDate = app.globalData.startDate.monthDay + ' ' + app.globalData.startDate.hours + ':' + app.globalData.startDate.minute;
      if (orderInfo == '' || orderInfo.openId == '' || orderInfo.name == '' || orderInfo.phone == '' || orderInfo.ordergetGPS == '' || orderInfo.orderbackGPS == '' || orderInfo.backPlace == '' || orderInfo.getPlace == '' || orderInfo.dordergetDate == '' || orderInfo.dordergetDate == undefined) {
        this.ClearMapGPS();
        wx.showToast({
          title: '请确认信息完整',
          icon: 'none',
          mask: true,
          duration: 2000
        })

      } else {
        console.log('网约车---', orderInfo)
        that.moveToLocation();
        app.request({
          url: "/reserveCarSave",
          data: orderInfo,
          success: function(res) {
            that.ClearMapGPS();
            that.moveToLocation();
            wx.showToast({
              title: '提交订单成功',
              icon: 'success',
              duration: 2000,
              mask: true,
              success: function() {
                setTimeout(function() {
                  wx.reLaunch({
                    url: '/pages/order/order'
                  })
                }, 2000);
              }
            })
          }, fail: function (res) {
            that.ClearMapGPS();
            that.moveToLocation();
          }
        })
        that.moveToLocation();
      }
    }
  },
  //地图左侧点击返回
  ClearMapGPS: function() {
    var that = this
    app.globalData.map.endAddress = '目的地';
    app.globalData.map.endLatitude = '';
    app.globalData.map.endLongitude = '';
    app.globalData.startDate = [];
    app.globalData.endDate = [];
    that.setData({
      markers: {},
      polyline:{
        points:{}
      },
      globalData: app.globalData,
      globalMapData: app.globalData.map,
      isGoBtn: false,
      isGotoBackBtn: false
    });
    console.log('ClearMapGPS----')
    that.moveToLocation();
    that.setData({
      scale: 20
    })
    this.setMapHeight();
  },
  onShareAppMessage: function(ops) {
    return {
      title: '广丰出行邀请您一起体验',
      path: 'pages/index/index',
      success: function(res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
      },
      fail: function(res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
  }
})